<?php
require_once __DIR__ . '/../models/User.php';
require_once __DIR__ . '/../utils/JwtHandler.php';

class AuthController
{
	private $db;
	private $userModel;
	private $jwtHandler;

	// 构造函数
	public function __construct($db)
	{
		$this->db = $db;
		$this->userModel = new User($db);
		$this->jwtHandler = new JwtHandler();
	}

	// 登录
	public function login()
	{
		// 获取请求数据
		$data = json_decode(file_get_contents('php://input'), true);

		if (empty($data['email']) || empty($data['password'])) {
			http_response_code(400);
			echo json_encode(['error' => 'Email and password are required']);
			return;
		}

		$user = $this->userModel->findByEmail($data['email']);

		if (!$user || !$this->userModel->verifyPassword($user, $data['password'])) {
			http_response_code(401);
			echo json_encode(['error' => 'Invalid credentials']);
			return;
		}

		$token = $this->jwtHandler->generateToken($user['id']);

		echo json_encode([
			'message' => 'Login successful',
			'token' => $token,
			'user' => [
				'id' => $user['id'],
				'email' => $user['email'],
				'username' => $user['username']
			]
		]);
	}

	//  注册
	public function register()
	{
		$data = json_decode(file_get_contents('php://input'), true);

		// // 验证必填字段
		// if (empty($data['email']) || empty($data['password'])) {
		// 	http_response_code(400);
		// 	echo json_encode(['error' => 'Email and password are required']);
		// 	return;
		// }

		try {
			// 创建用户
			$user = $this->userModel->create(
				$data['email'],
				$data['password']
			);

			// 注册成功后自动登录
			$token = $this->jwtHandler->generateToken($user['id']);

			http_response_code(201);
			echo json_encode([
				'message' => 'Registration successful',
				'token' => $token,
				'user' => [
					'id' => $user['id'],
					'email' => $user['email'],
					'username' => $user['username'] ?? null
				]
			]);
		} catch (Exception $e) {
			http_response_code(400);
			echo json_encode(['error' => $e->getMessage()]);
		}
	}
}
?>